package com.bgds.sys.socket;

import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.cisdi.data.common.exception.BusinessException;

/**
 * 备份的 弃用
 *
 * @param null
 * @author chenchao
 * @date 2021/11/3
 * @return
 */
public class BackSocketClient {

    private static Logger logger = LoggerFactory.getLogger(SocketClient.class);

    //连接服务器的IP
    public String ip = null;
    //连接服务器的端口
    public Integer port = null;
    //套节字对象
    private Socket socket = null;
    //超时时间，以毫秒为单位
    private Integer timeout = 2000;

	public BackSocketClient(String ip, Integer port) {
		this.ip = ip;
		this.port = port;
	}


    /**
     * 打开连接
     */
    public void open() {
        try {
            socket = new Socket();
            socket.connect(new InetSocketAddress(ip, port), timeout);//设置连接请求超时时间
            socket.setKeepAlive(true);//开启保持活动状态的套接字
            socket.setSoTimeout(timeout);//设置超时时间
        } catch (UnknownHostException e) {
            logger.error(e.getMessage(), e);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
    }

    /**
     * 发送数据（同步返回）
     *
     * @param csocket
     * @param data
     * @return
     */
    public String send(byte[] data) {

        String resultString = null;

        DataOutputStream out = null;
        try {
            out = new DataOutputStream(socket.getOutputStream());

            out.write(data);
            out.flush();

        } catch (Exception e) {
            throw new BusinessException(e.getMessage(), e);
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    logger.error("DataOutputStream out 关闭异常：", e);
                }
            }
        }

        return resultString;
    }

    public void close() {
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException e) {
                logger.warn(e.getLocalizedMessage(), e);
            }
        }
    }

}
